const path = require('path')
const app = require('electron').app
const appPath = app.getAppPath()
const express = require('express')
const websiteApp = express()
const wwwroot = path.join(appPath, '../webrtc-client')
// websiteApp.use('*', function (req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With')
//   res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS')
//   if (req.method === 'OPTIONS') {
//     res.send(200)
//   } else {
//     next()
//   }
// })
websiteApp.use('/static', express.static(wwwroot))
const server = require('http').createServer(websiteApp)
const wsServer = require('socket.io')(server, { cors: true })
let wsPort = 7650
let clientsLive = []
let clients = null
let serversLive = []
let servers = null
let socketIODict = {}


/**
 * 创建websocket服务器
 * @param {Number} options/port 端口号
 * @param {Function} options/onconnect 发生连接时的回调函数
 * @param {Function} options/onmessage 收到信息时的回调函数
 * @param {Function} options/ondisconnect 有连接断开时的回调函数
 */
const createWsServer = (options = {}) => {
  clients = wsServer.of('/clients')
  servers = wsServer.of('/servers')
  // 函数定义 - 客户端群组
  clients.on('connect', SocketIO => {
    console.log('有客户端接入', SocketIO.id)
    clientsLive.push(SocketIO.id)
    socketIODict[SocketIO.id] = {io: SocketIO}
    options.onconnect && options.onconnect(SocketIO)

    SocketIO.on('message', (data) => {
      console.log('收到信息', SocketIO.id)
      options.onmessage && options.onmessage(data)
    })

    SocketIO.on('disconnect', () => {
      console.log('有客户端断开', SocketIO.id)
      clientsLive = clientsLive.filter(sid => sid != SocketIO.id)
      delete socketIODict[SocketIO.id]
      options.ondisconnect && options.ondisconnect(SocketIO)
      servers && servers.emit('remoteLeave', {id: SocketIO.id})
    })

    // WebRTC方案
    // let dataTemplate = {id: SocketIO.id, data: {}}
    SocketIO.on('screenshot', (data) => {
      console.log('clients screenshot:', SocketIO.id)
      servers && servers.emit('screenshot', {id: SocketIO.id, data})
    })
    SocketIO.on('description', (data) => {
      console.log('clients description:', SocketIO.id)
      servers && servers.emit('remoteDescription', {id: SocketIO.id, data})
    })
    SocketIO.on('candidate', (data) => {
      console.log('clients candidate:', SocketIO.id)
      servers && servers.emit('remoteCandidate', {id: SocketIO.id, data})
    })
    SocketIO.on('join', (data) => {
      console.log('clients join:', SocketIO.id)
      servers && servers.emit('remoteJoin', {id: SocketIO.id, data})
    })
    SocketIO.on('leave', (data) => {
      console.log('clients leave:', SocketIO.id)
      servers && servers.emit('remoteLeave', {id: SocketIO.id, data})
    })
  })
  // 函数定义 - 服务端群组
  servers.on('connect', SocketIO => {
    console.log('有服务端接入', SocketIO.id)
    serversLive.push(SocketIO.id)
    socketIODict[SocketIO.id] = {io: SocketIO}
    options.onconnect && options.onconnect(SocketIO)

    SocketIO.on('message', (data) => {
      console.log('收到信息', SocketIO.id, data)
      clients && clients.emit('message', data)
      options.onmessage && options.onmessage(data)
    })

    SocketIO.on('disconnect', () => {
      console.log('有服务端断开', SocketIO.id)
      serversLive = serversLive.filter(sid => sid != SocketIO.id)
      delete socketIODict[SocketIO.id]
      options.ondisconnect && options.ondisconnect(SocketIO)
      clients && clients.emit('closeConnection', {id: SocketIO.id})
    })

    // WebRTC方案
    SocketIO.on('screenshot', (data) => {
      console.log('servers screenshot:', SocketIO.id)
      clients && clients.emit('screenshot', {id: SocketIO.id, data})
    })
    SocketIO.on('resetConnection', (data) => {
      console.log('servers resetConnection:', SocketIO.id, data)
      let ids = data.ids || []
      ids.forEach(id => {
        socketIODict[id] && socketIODict[id].io.emit('resetConnection', {id: SocketIO.id, data: data.data})
      })
    })
    SocketIO.on('description', (data) => {
      console.log('servers description:', SocketIO.id)
      if (!data.id) return
      socketIODict[data.id] && socketIODict[data.id].io.emit('remoteDescription', {id: SocketIO.id, data: data.data})
    })
    SocketIO.on('candidate', (data) => {
      console.log('servers candidate:', SocketIO.id)
      if (!data.id) return
      socketIODict[data.id] && socketIODict[data.id].io.emit('remoteCandidate', {id: SocketIO.id, data: data.data})
    })
    SocketIO.on('canJoin', (data) => {
      console.log('servers canJoin:', SocketIO.id)
      if (!data.id) return
      socketIODict[data.id] && socketIODict[data.id].io.emit('canJoin', {id: SocketIO.id})
    })
    SocketIO.on('closeConnection', (data) => {
      console.log('servers leave:', SocketIO.id)
      if (data.ids) {
        data.ids.forEach(id => {
          socketIODict[id] && socketIODict[id].io.emit('closeConnection', {id: SocketIO.id})
        })
      }
    })
  })
  server.listen(wsPort)
}

// 启动服务
const start = (options = {}) => {
  wsPort = options.port || wsPort
  createWsServer(options)
}

// 关闭服务
const stop = () => {
  wsServer.close()
  server.close()
}

// 发送数据
const send = (data) => {
  if (!data) return
  clients.send(data)
}

// 获取服务器对象
const getServer = () => {
  return wsServer
}

module.exports = {
  getServer,
  start,
  stop,
  send
}
